package com.diligreat.interceptor; 

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.util.TokenProcessor;
import org.apache.struts2.ServletActionContext;

import com.diligreat.util.Constants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**  
 * @Author Bruce 
 * @Date 2012-10-6
 * @Comments 对于要校验表单重复提交的方法配置此拦截器。表单内需有隐藏域"submitFlag"、"token"
 */
//public class TokenInterceptor extends AbstractInterceptor {
public class TokenInterceptor extends  MethodFilterInterceptor {
	private static final long serialVersionUID = 1L;
	
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		System.out.println("TokenInterceptor...");
		String result = null;
		ActionContext actionContext = invocation.getInvocationContext();
		Map<String, Object> session = actionContext.getSession(); 
		Map<String, Object> param = actionContext.getParameters();
		String sessionToken = (String) session.get(Constants.TOKEN_KEY);
		String[] submitFlag = (String[]) param.get(Constants.SUBMIT_FLAG);
		String[] formToken = (String[]) param.get(Constants.TOKEN_KEY);
		
		HttpServletRequest request = (HttpServletRequest) actionContext.get(ServletActionContext.HTTP_REQUEST);
		//String sessionId = request.getSession().getId();
		String token = TokenProcessor.getInstance().generateToken(request);
		if(sessionToken == null){
			session.put(Constants.TOKEN_KEY, token);
			try {
				result = invocation.invoke();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(submitFlag == null || !"true".equals(submitFlag[0])){
			//进入表单页面
			request.setAttribute(Constants.TOKEN_KEY,token);//把生成的token加入request
			session.put(Constants.TOKEN_KEY, token);
			//result = invocation.invoke();
			result = Action.INPUT;
		}else if(formToken == null){
			actionContext.put("message", "页面表单没有token");
			result = Action.ERROR;
		}else if(!sessionToken.equals(formToken[0])){
			actionContext.put("message", "重复提交");
			result = Action.ERROR;
		}else{
			actionContext.put("message", "操作成功");
			//session.remove(TOKEN_KEY);//删除session中的token
			session.put(Constants.TOKEN_KEY, "");
			try {
				result = invocation.invoke();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("return "+result);
		return result;
	}

/*	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}*/


}
 